//
//  DDRViewController.m
//  Lottolandia
//
//  Created by Luca D'Antona on 23/11/13.
//  Copyright (c) 2013 Quelli for Lotto. All rights reserved.
//

#import "DDRViewController.h"
#import <QuartzCore/QuartzCore.h>

@interface DDRViewController ()

@end

@implementation DDRViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    bleShield = [[BLE alloc] init];
    [bleShield controlSetup];
    bleShield.delegate = self;
    [self BLEShieldScan:nil];
    
    arrowUp = [UIImage imageNamed:@"up"];
    arrowUpOff = [UIImage imageNamed:@"upOff"];
    arrowUpOn = [UIImage imageNamed:@"upOn"];
    arrowDown = [UIImage imageNamed:@"down"];
    arrowDownOff = [UIImage imageNamed:@"downOff"];
    arrowDownOn = [UIImage imageNamed:@"downOn"];
    arrowLeft = [UIImage imageNamed:@"left"];
    arrowLeftOff = [UIImage imageNamed:@"leftOff"];
    arrowLeftOn = [UIImage imageNamed:@"leftOn"];
    arrowRight = [UIImage imageNamed:@"right"];
    arrowRightOff = [UIImage imageNamed:@"rightOff"];
    arrowRightOn = [UIImage imageNamed:@"rightOn"];
    
    self.counter.transform = CGAffineTransformMakeScale(0.1, 0.1);
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

// Called when scan period is over to connect to the first found peripheral
-(void) connectionTimer:(NSTimer *)timer
{
    if(bleShield.peripherals.count > 0)
    {
        [bleShield connectPeripheral:[bleShield.peripherals objectAtIndex:0]];
    }
    else
    {
        [self.spinner stopAnimating];
    }
}

-(void) bleDidReceiveData:(unsigned char *)data length:(int)length
{
    NSData *d = [NSData dataWithBytes:data length:length];
    NSString *s = [[NSString alloc] initWithData:d encoding:NSUTF8StringEncoding];
    NSNumber *number = [NSNumber numberWithChar:(*data)];
    
    NSLog(@"BLE data: %@", number);
    
    self.label.text = number.stringValue;
    
    switch (s.intValue) {
        case 0: {
            NSLog(@"Avanti");
            [UIView animateWithDuration:0.2 animations:^{
                [self.arrowUpStatic setSelected:YES];
            } completion:^(BOOL finished) {
                [self.arrowUpStatic setSelected:NO];
            }];
            
            break;
        }
        case 1: {
            NSLog(@"Indietro");
            [UIView animateWithDuration:0.2 animations:^{
                [self.arrowDownStatic setSelected:YES];
            } completion:^(BOOL finished) {
                [self.arrowDownStatic setSelected:NO];
            }];
            break;
        }
        case 2: {
            NSLog(@"Sinistra");
            [UIView animateWithDuration:0.2 animations:^{
                [self.arrowLeftStatic setSelected:YES];
            } completion:^(BOOL finished) {
                [self.arrowLeftStatic setSelected:NO];
            }];
            break;
        }
        case 3: {
            NSLog(@"Destra");
            [UIView animateWithDuration:0.2 animations:^{
                [self.arrowRightStatic setSelected:YES];
            } completion:^(BOOL finished) {
                [self.arrowRightStatic setSelected:NO];
            }];
            break;
        }
        default:
            break;
    }
    
}

NSTimer *rssiTimer;

-(void) readRSSITimer:(NSTimer *)timer
{
    [bleShield readRSSI];
}

- (void) bleDidDisconnect
{
    [self.buttonConnect setTitle:@"Connect" forState:UIControlStateNormal];
    
    [rssiTimer invalidate];
}

-(void) bleDidConnect
{
    [self.spinner stopAnimating];
    [self.buttonConnect setTitle:@"Disconnect" forState:UIControlStateNormal];
    
    // Schedule to read RSSI every 1 sec.
    rssiTimer = [NSTimer scheduledTimerWithTimeInterval:(float)1.0 target:self selector:@selector(readRSSITimer:) userInfo:nil repeats:YES];
}

-(void) bleDidUpdateRSSI:(NSNumber *)rssi
{
    self.labelRSSI.text = rssi.stringValue;
}

- (IBAction)BLEShieldSend:(id)sender
{
    NSString *s;
    NSData *d;
    
    if (self.textField.text.length > 16)
        s = [self.textField.text substringToIndex:16];
    else
        s = self.textField.text;
    
    s = [NSString stringWithFormat:@"%@\r\n", s];
    d = [s dataUsingEncoding:NSUTF8StringEncoding];
    
    [bleShield write:d];
}

- (IBAction)BLEShieldScan:(id)sender
{
    if (bleShield.activePeripheral)
        if(bleShield.activePeripheral.isConnected)
        {
            [[bleShield CM] cancelPeripheralConnection:[bleShield activePeripheral]];
            return;
        }
    
    if (bleShield.peripherals)
        bleShield.peripherals = nil;
    
    [bleShield findBLEPeripherals:3];
    
    [NSTimer scheduledTimerWithTimeInterval:(float)3.0 target:self selector:@selector(connectionTimer:) userInfo:nil repeats:NO];
    
    [self.spinner startAnimating];
}



- (IBAction)start:(id)sender {
    self.counter.hidden = NO;
    [UIView transitionWithView:self.counter
                      duration:0.7
                       options:UIViewAnimationOptionCurveEaseInOut
                    animations:^{
                        //[self.counter layoutIfNeeded];
                        //self.counter.font = [UIFont fontWithName:@"ArialMT" size:1000.0];
                        self.counter.transform = CGAffineTransformMakeScale(1, 1);
                        self.counter.alpha = 0.0;
                    }completion:^(BOOL finished) {
                        self.counter.transform = CGAffineTransformMakeScale(0.1, 0.1);
                        self.counter.text = @"2";
                        self.counter.alpha = 1.0;
                        [UIView transitionWithView:self.counter
                                          duration:0.7
                                           options:UIViewAnimationOptionCurveEaseInOut
                                        animations:^{
                                            //[self.counter layoutIfNeeded];
                                            //self.counter.font = [UIFont fontWithName:@"ArialMT" size:1000.0];
                                            self.counter.transform = CGAffineTransformMakeScale(1, 1);
                                            self.counter.alpha = 0.0;
                                        } completion:^(BOOL finished) {
                                            self.counter.transform = CGAffineTransformMakeScale(0.1, 0.1);
                                            self.counter.text = @"1";
                                            self.counter.alpha = 1.0;
                                            
                                            [UIView transitionWithView:self.counter
                                                              duration:0.7
                                                               options:UIViewAnimationOptionCurveEaseInOut
                                                            animations:^{
                                                                //[self.counter layoutIfNeeded];
                                                                //self.counter.font = [UIFont fontWithName:@"ArialMT" size:1000.0];
                                                                self.counter.transform = CGAffineTransformMakeScale(1, 1);
                                                                self.counter.alpha = 0.0;
                                                                
                                                                
                                                            } completion:^(BOOL finished) {
                                                                [NSTimer scheduledTimerWithTimeInterval:(float)1.0 target:self selector:@selector(generateArrow) userInfo:nil repeats:YES];
                                                                NSString *soundFile = [[NSBundle mainBundle] pathForResource:@"gangnam" ofType:@"mp3"];
                                                                NSURL *url = [NSURL fileURLWithPath:soundFile];
                                                                NSError *error;
                                                                player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
                                                                if (player) {
                                                                    player.delegate = self;
                                                                    [player play];
                                                                }
                                                            }];
                                        }
                         
                         ];
                    }];
    
    //[NSTimer scheduledTimerWithTimeInterval:(float)1.0 target:self selector:@selector(generateArrow) userInfo:nil repeats:YES];
    
}

- (void)generateArrow {
    int index = arc4random() % 4;
    
    UIButton *arrowBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:arrowBtn];
    
    switch (index) {
        case 0:
            [arrowBtn setImage:arrowUp forState:UIControlStateNormal];
            [arrowBtn setImage:arrowUpOff forState:UIControlStateSelected];
            [arrowBtn setFrame:CGRectMake(self.arrowUpStatic.frame.origin.x, self.view.frame.size.height+self.arrowUpStatic.frame.size.height, 50, 50)];
            
            break;
        case 1:
            [arrowBtn setImage:arrowDown forState:UIControlStateNormal];
            [arrowBtn setImage:arrowDownOff forState:UIControlStateSelected];
            [arrowBtn setFrame:CGRectMake(self.arrowDownStatic.frame.origin.x, self.view.frame.size.height+self.arrowDownStatic.frame.size.height, 50, 50)];
            
            break;
        case 2:
            [arrowBtn setImage:arrowLeft forState:UIControlStateNormal];
            [arrowBtn setImage:arrowLeftOff forState:UIControlStateSelected];
            [arrowBtn setFrame:CGRectMake(self.arrowLeftStatic.frame.origin.x, self.view.frame.size.height+self.arrowLeftStatic.frame.size.height, 50, 50)];
            
            break;
        case 3:
            [arrowBtn setImage:arrowRight forState:UIControlStateNormal];
            [arrowBtn setImage:arrowRightOff forState:UIControlStateSelected];
            [arrowBtn setFrame:CGRectMake(self.arrowRightStatic.frame.origin.x, self.view.frame.size.height+self.arrowRightStatic.frame.size.height, 50, 50)];
            
            break;
            
        default:
            break;
    }
    
    
    float time = 2.0;
    
    //[self animateArrow:arrowBtn];
    [UIView animateWithDuration:time delay:0.0 options:UIViewAnimationOptionCurveLinear animations:^{
        CGRect frame = arrowBtn.frame;
        frame.origin.y = -arrowBtn.frame.size.height;
        arrowBtn.frame = frame;
    } completion:^(BOOL finished) {
        
    }];
}

- (IBAction)backToPark:(id)sender {
    if (player)
        [player stop];
    [self dismissViewControllerAnimated:YES completion:nil];
}


@end
